<template>
  <div class="user-info">
    <div class="header">
      <div class="title">个人资料</div>
    </div>
    <div class="content">
      <div class="user-info-card">
        <div class="card-header">
          <div class="avatar">
            <span class="icon" v-html="Avatar"></span>
          </div>
          <div class="base-info">
            <div class="name-text">{{ userInfo.userName }}</div>
            <div class="school-text">
              <div class="prop-name">角色信息</div>
              <div class="prop-value">
                {{ roleIInfo }}
              </div>
            </div>
          </div>
        </div>
        <el-divider />
        <div class="info">
          <div class="prop-name">任教信息</div>
          <div class="prop-value">{{ teachingInfo }}</div>
        </div>
        <el-divider />
        <div class="info-wrapper">
          <div class="info">
            <div class="prop-name">手机号</div>
            <div class="prop-value">
              {{ accountInfo?.phone }}
            </div>
            <div v-if="!phone.isEdit" class="change-btn" @click="changePhone">
              修改
            </div>
          </div>
          <template v-if="phone.isEdit">
            <div class="info">
              <div class="prop-name">新手机号</div>
              <div class="prop-value">
                <el-input
                  class="input"
                  v-model="phone.content"
                  placeholder="请输入新手机号"
                ></el-input>
              </div>
              <div class="change-btn" @click="handleSendPhoneCode">
                {{ interval ? `重新发送(${phone.time})` : '发送验证码' }}
              </div>
            </div>

            <div class="info" v-if="phone.isEdit">
              <div class="prop-name">验证码</div>
              <div class="prop-value">
                <el-input
                  class="input"
                  v-model="phone.code"
                  placeholder="请输入验证码"
                ></el-input>
              </div>
              <div class="btn-box">
                <button class="btn cancel-btn" @click="changePhone">
                  取消
                </button>
                <button class="btn save-btn" @click="saveNewPhone">保存</button>
              </div>
            </div>
          </template>
        </div>

        <el-divider />
        <div class="info-wrapper">
          <div class="info" v-if="pwd.isChange">
            <div class="prop-name">原登录密码</div>
            <div class="prop-value">
              <el-input
                class="input"
                placeholder="请输入原密码"
                v-model="pwd.origin"
              ></el-input>
            </div>
          </div>
          <div class="info" v-else>
            <div class="prop-name">登录密码</div>
            <div class="prop-value">
              {{ '********' }}
            </div>
            <div @click="changePwd" class="change-btn">修改</div>
          </div>
          <template v-if="pwd.isChange">
            <div class="info">
              <div class="prop-name">新登录密码</div>
              <div class="prop-value">
                <el-input
                  class="input"
                  placeholder="请输入新密码"
                  v-model="pwd.new"
                ></el-input>
              </div>
            </div>
            <div class="info">
              <div class="prop-name">确认新密码</div>
              <div class="prop-value">
                <el-input
                  class="input"
                  placeholder="请确认新密码"
                  v-model="pwd.againNew"
                ></el-input>
              </div>
              <div class="btn-box">
                <button class="btn cancel-btn" @click="changePwd">取消</button>
                <button class="btn save-btn" @click="savePwd">保存</button>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { computed, ref, reactive } from 'vue'
import Avatar from '@/assets/images/common/i-avatar.svg?raw'
import {
  getAccountInfo,
  sendPhoneCode,
  verifyPhoneCode,
  updatePwd
} from '@/apis/auth.js'
import { postLogout } from '@/apis'
import { useAuthStore, useKnowledgeStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import CryptoJs from 'crypto-js'

const CLIENT_ID = '1714986596724'
const CLIENT_SECRET = 'BBE58FBF2D92A594A0A6B906CC548A42'

const { reset } = useKnowledgeStore()
const router = useRouter()
const authStore = useAuthStore()
const userInfo = computed(() => authStore.userInfo)
const teachingInfo = computed(() =>
  authStore.globalSubjectList
    .map(item => `${item.section_name}${item.subject_name}`)
    .join(' ')
)

const roleIInfo = computed(() => {
  return authStore.filteredRoles.map(item => `${item.role_name}`).join('/')
})

const accountInfo = ref()
const getInfo = async () => {
  const { data } = await getAccountInfo({
    person_id: +authStore.userInfo.userId
  })
  accountInfo.value = data || {}
  console.log('account info', accountInfo.value, data)
}
getInfo()

// 修改手机号
const phone = reactive({
  isEdit: false,
  content: accountInfo.value?.phone || '',
  code: '',
  time: 60
})

const isPhoneNum = computed(() => {
  return /^1[3456789]\d{9}$/.test(phone.content)
})
const changePhone = () => {
  if (phone.isEdit) {
    phone.content = ''
    phone.code = ''
    phone.isEdit = false
    if (interval.value) {
      clearInterval(interval.value)
      interval.value = null
    }
  } else {
    phone.isEdit = true
  }
}

const checkPhone = () => {
  let flag = false
  if (!phone.content) {
    ElMessage.warning('请输入手机号')
  } else if (!isPhoneNum.value) {
    ElMessage.warning('手机号格式错误，请检查！')
  } else {
    flag = true
  }
  return flag
}

const checkCode = () => {
  let flag = false
  if (!phone.code) {
    ElMessage.warning('验证码不能为空')
  } else flag = true
  return flag
}

const interval = ref()
const handleSendPhoneCode = async () => {
  if (interval.value) {
    ElMessage.warning('请勿重复获取验证码')
  } else if (checkPhone()) {
    interval.value = setInterval(() => {
      phone.time--
      if (phone.time <= 0) {
        clearInterval(interval.value)
        interval.value = null
      }
    }, 1000)
    await sendPhoneCode({
      client_id: CLIENT_ID,
      phone: phone.content,
      person_id: +authStore.userInfo.userId
    })
    ElMessage.success('验证码已发送！')
  }
}

const saveNewPhone = async () => {
  if (checkCode()) {
    const { code, msg } = await verifyPhoneCode({
      client_id: CLIENT_ID,
      phone: phone.content,
      code: phone.code
    })
    if (code !== 100200) {
      ElMessage.error(msg || '修改手机号失败')
    } else {
      ElMessage.success('手机号修改成功')
      changePhone()
      getInfo()
    }
  }
}

// 修改密码
const pwd = reactive({
  isChange: false,
  origin: '',
  new: '',
  againNew: ''
})

const matchPwd = computed(() => {
  return /^.{6,}$/.test(pwd.new)
})

const changePwd = () => {
  if (pwd.isChange) {
    pwd.new = ''
    pwd.againNew = ''
    pwd.origin = ''
    pwd.isChange = false
  } else {
    pwd.isChange = true
  }
}

const checkPwd = () => {
  let flag = false
  if (!pwd.new) {
    ElMessage.warning('密码不能为空')
  } else if (!matchPwd.value) {
    ElMessage.warning('密码必须包含字母、数字、特殊字符，且至少6位')
  } else {
    flag = true
  }
  return flag
}

const savePwd = async () => {
  if (!pwd.origin) {
    ElMessage.warning('请输入原密码！')
  } else if (pwd.new !== pwd.againNew) {
    ElMessage.warning('两次输入的密码不一致，请检查！')
  } else if (checkPwd()) {
    const { code, msg } = await updatePwd({
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      password: CryptoJs.MD5(pwd.origin).toString(),
      new_password: CryptoJs.MD5(pwd.new).toString(),
      person_id: +authStore.userInfo.userId
    })
    if (code !== 100200) {
      ElMessage.error(msg)
    } else {
      ElMessage.success('密码修改成功，系统将退出，请重新登录！')
      setTimeout(() => {
        logout()
      }, 500)
    }
  }
}

const logout = async () => {
  const { sessionId, userId, userType, platform } = authStore.userInfo
  const params = {
    ACCESSTOKEN: sessionId,
    userId,
    userType,
    platform
  }
  const res = await postLogout(params)
  if (res.F_responseNo === 10000) {
    ElMessage.success('退出成功')
    reset()
    authStore.resetAllStates()
    router.push('/login')
  } else {
    ElMessage.error(res.F_responseMsg)
  }
}
</script>
<style lang="less" scoped>
.user-info {
  .header {
    height: 50px;
    .title {
      font-size: 22px;
      font-weight: 500;
    }
  }
  .content {
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 15px;
    background: linear-gradient(
      180deg,
      rgba(213, 228, 251, 0.55) 0%,
      rgba(255, 255, 255, 0) 22%
    );
    background-color: #fff;
    height: 90vh;
    .user-info-card {
      width: 916px;
      margin: 0 auto;
      height: 700px;
      .card-header {
        display: flex;
        .avatar {
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
          width: 158px;
          height: 158px;
          border-radius: 8px;
          background: #d4e6ff;
          .icon {
            display: inline-block;
            color: #fff;
            width: 98px;
            height: 98px;
          }
        }
        .base-info {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: flex-start;
          font-size: 22px;
          font-weight: 500;
          margin-left: 22px;
          .name-text {
            text-align: center;
          }

          .school-text {
            display: flex;
            font-weight: 400;
          }
        }
      }
      .prop-name {
        width: 100px;
        font-size: 16px;
        font-weight: 500;
        color: @color-neutral-body;
      }
      .prop-value {
        flex: 1;
        font-size: 16px;
        word-break: keep-all;
      }
      .info {
        display: flex;
        align-items: center;
        width: 649px;
        margin-left: 180px;
        .change-btn {
          color: @color-brand-regular;
          cursor: pointer;
        }
      }
    }
  }

  .info-wrapper {
    display: flex;
    flex-direction: column;
    gap: 30px;
  }

  .btn-box {
    display: flex;
    gap: 10px;

    .btn {
      width: 76px;
      height: 30px;
      border: 1px solid @color-brand-regular;
      background-color: unset;
      font-size: 16px;
      font-weight: 500;
      cursor: pointer;
      border-radius: 3px;

      &.save-btn {
        color: #fff;
        background-color: @color-brand-regular;
      }

      &.cancel-btn {
        color: @color-brand-regular;
      }
    }
  }

  .input {
    width: 320px;

    :deep(.el-input__wrapper) {
      height: 36px;
    }
  }
}
</style>
